<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />
    <title>简单的视差滚动</title>
  </head>
  <body>
    <section>
      <img src="../images/bg.jpg" alt="" id="bg" />
      <img src="../images/moon.png" alt="" id="moon" />
      <img src="../images/mountain.png" alt="" id="mountain" />
      <img src="../images/road.png" alt="" id="road" />
      <h2 id="text">Moon Light</h2>
    </section>
    <script>
      let bg = document.getElementById('bg')
      let moon = document.getElementById('moon')
      let mountain = document.getElementById('mountain')
      let road = document.getElementById('road')
      let text = document.getElementById('text')

      window.addEventListener('scroll', function () {
        let value = window.scrollY
        bg.style.top = value * 0.5 + 'px'
        moon.style.left = -value * 0.5 + 'px'
        mountain.style.top = -value * 0.15 + 'px'
        road.style.top = value * 0.15 + 'px'
        text.style.top = value * 1 + 'px'
        // 新增文字随滚动条滚动透明度变化
        text.style.opacity = 1 - value / 250
      })
    </script>
  </body>
</html>
